package com.blockmeta.bbs.businesslibrary.websocket;


import com.blockmeta.bbs.businesslibrary.pojo.websocket.BasePOJO;

import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


/**
 * Created by websocket
 */
public class LinkQueue
{
    // 等待連線建立後 不可保留發出的封包
    public static int[] QueuePacket_BlackList = {

    };

    public enum QueueType
    {
        Write, writeAndWait, writeEncrypt,writeEncryptAndWait
    }

    public static class QueuePacket
    {
        public QueueType m_enType;
        public BasePOJO m_packet;
        public int m_nParam;
        public WaitSendQueue.IWaitListener m_listener;

        public QueuePacket(QueueType type, int param, BasePOJO pkt, WaitSendQueue.IWaitListener listener)
        {
            m_enType = type;
            m_packet = pkt;
            m_nParam = param;
            m_listener = listener;
        }
    }

    private ConnectManager m_connManager;
    private ArrayList<Integer> m_arBlackList;
    private Queue<QueuePacket> m_queuePacket;  // 保留 連線後發出的封包
    private final static int MaxPacketNum = 5;

    public LinkQueue(ConnectManager mgr)
    {
        m_connManager = mgr;
        m_queuePacket = new ConcurrentLinkedQueue<QueuePacket>();
        m_arBlackList = new ArrayList<Integer>();

        for(int pktNo : QueuePacket_BlackList)
        {
            m_arBlackList.add(pktNo);
        }
    }

    public void push(QueuePacket pkt)
    {
//        if (m_arBlackList.contains(pkt.m_packet.get_pt()) == false)
//        {
        if(m_queuePacket.size() > MaxPacketNum)
        {
            m_queuePacket.poll();
        }
        m_queuePacket.add(pkt);
//        }
    }

    public QueuePacket pop()
    {
        return m_queuePacket.poll();
    }

    public void sendAll()
    {
        QueuePacket pkt = m_queuePacket.poll();

        while(pkt != null)
        {
            switch(pkt.m_enType)
            {
                case Write:
                    m_connManager.write(pkt.m_packet);
                    break;
                case writeAndWait:
//                    m_connManager.writeAndWait(pkt.m_packet, pkt.m_nParam, pkt.m_listener);
                    break;
                case writeEncrypt:
//                    m_connManager.writeEncrypt(pkt.m_packet);
                    break;
                case writeEncryptAndWait:
//                    m_connManager.writeEncryptAndWait(pkt.m_packet, pkt.m_nParam, pkt.m_listener);
                    break;
            }
            pkt = m_queuePacket.poll();
        }
    }

    public void clear()
    {
        m_queuePacket.clear();
    }
}
